import requests
import json
import time

import send
import search
import os
 
# 钉钉机器人的Webhook URL
DINGTALK_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=YOUR_ACCESS_TOKEN'  # 替换为实际的Webhook地址

# 数据存储路径
LAST_DATA_FILE = 'last_data.json'

def load_last_data():
    """加载上次发送的数据"""
    # 尝试使用正确的编码方式读取文件
    try:
        with open(LAST_DATA_FILE, 'r', encoding='utf-8') as file:
            return json.load(file)
    except UnicodeDecodeError:
        # 如果 UTF-8 解码失败，尝试使用 GBK 或其他编码
        with open(LAST_DATA_FILE, 'r', encoding='gbk') as file:
            return json.load(file)

    
def send_dingtalk_message(data):
    """发送钉钉消息"""
    markdown_message = {
        "msgtype":"feedCard",
        "feedCard": {
            "links": data
        }
    }
    is_send_all = False
    send.send_ding_message(markdown_message,is_send_all)
    print("钉钉推送结果:", markdown_message)

    

def process_data(last_data, current_data):
    """处理数据"""
    #保存数据
    with open(LAST_DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(current_data, f, ensure_ascii=False, indent=4)

    # 提取上次数据的 publishTime 用于比较
    last_categoryId = {item['categoryId'] for item in last_data}

    # 找出新增的数据
    new_data = [item for item in current_data if item['categoryId'] not in last_categoryId]

    # 如果有新增数据，输出并更新 last_data.json
    if new_data:
        print("新增数据:", new_data)
        send_data = []
        for item in new_data:
            cur_item = {
                    "title": item['title'] + '价格'+item['price'], 
                    "messageURL": item['target_url'], 
                    "picURL": item['picUrl']
            }
            send_data.append(cur_item)

        return send_data
    else:
        print("没有新增的数据。")
        return []
    

    
   

def main():
    while True:
        # 抓取数据
        _m_h5_tk = '5aa35d483ce25b4d3a57ffe4321a912c_1739182493247'
        _m_h5_tk_enc = '0cd188b8d4cdd1ebf7882662ea9ad20b'
        # 时间间隔 :推送多长时间以前的数据MS
        space_time = 10*60*60*1000
        current_data = search.get_fetch_data(_m_h5_tk, _m_h5_tk_enc,space_time)

        # 加载上次发送的数据
        last_data = load_last_data()

        # 对两次数据进行处理
        send_data = process_data(last_data,current_data)
        if len(send_data) > 0:
            send_dingtalk_message(send_data)
    

        # 每10秒执行一次
        time.sleep(60)

if __name__ == "__main__":
    main()
